import 'dart:io';

import 'package:dio/dio.dart';

class DioClient {
  Dio _dio;

  DioClient({required Dio dio}) : this._dio = dio;

  final CancelToken _cancelToken = new CancelToken();

  /// GET 请求
  Future get(
    String path, {
    Map<String, dynamic>? params,
    Options? options,
    CancelToken? cancelToken,
    bool? needTip = false,
  }) async {
    Options requestOptions = options ?? Options();
    Options _new = requestOptions.copyWith(extra: {'needTip': needTip});
    var response = await _dio.get(path, queryParameters: params, options: _new, cancelToken: _cancelToken);
    return response.data;
  }

  /// POST 请求
  Future post(
    String path, {
    Map<String, dynamic>? params,
    data,
    Options? options,
    CancelToken? cancelToken,
    bool? needTip = false,
  }) async {
    Options requestOptions = options ?? Options();
    Options _new = requestOptions.copyWith(extra: {'needTip': needTip});
    var response = await _dio.post(path, data: data, queryParameters: params, options: _new, cancelToken: _cancelToken);
    return response.data;
  }

  /// PUT 请求
  Future put(
    String path, {
    data,
    Map<String, dynamic>? params,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    Options requestOptions = options ?? Options();
    var response =
        await _dio.put(path, data: data, queryParameters: params, options: requestOptions, cancelToken: _cancelToken);
    return response.data;
  }

  /// DELETE 请求
  Future delete(
    String path, {
    data,
    Map<String, dynamic>? params,
    Options? options,
    CancelToken? cancelToken,
    bool? needTip = false,
  }) async {
    Options requestOptions = options ?? Options();
    Options _new = requestOptions.copyWith(extra: {'needTip': needTip});
    var response =
        await _dio.delete(path, data: data, queryParameters: params, options: _new, cancelToken: _cancelToken);
    return response.data;
  }

  /// POST 文件上传
  Future postMultipart(
    String path, {
    required List<String> filePaths,
    required Map<String, dynamic> params,
    Options? options,
    CancelToken? cancelToken,
    bool? needTip = false,
  }) async {
    Options requestOptions = options ?? Options();
    Options _new = requestOptions.copyWith(extra: {'needTip': needTip});
    List<File> files = filePaths.where((element) => element.isNotEmpty).map((e) => File(e)).toList();
    List<MultipartFile> _files = [];
    for (File item in files) {
      MultipartFile file = await MultipartFile.fromFile(item.path);
      _files.add(file);
    }
    if (requestOptions.headers == null) {
      requestOptions.headers = {};
    }
    requestOptions.headers!['content-type'] = 'multipart/form-data';
    params['files'] = _files;
    FormData formData = FormData.fromMap(params);
    var response = await _dio.post(
      path,
      data: formData,
      options: _new,
      cancelToken: cancelToken ?? _cancelToken,
    );
    return response.data;
  }
}
